package cn.ddiancan.schedule.task.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.ddiancan.xddcloud.ddccore.cache.XddCloudCacheClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class DistributedLockService {

    private final XddCloudCacheClient xddCloudCacheClient;


    public boolean tryLock(String lockKey, long timeout) {
        Boolean success = xddCloudCacheClient.putIfAbsent(lockKey, "locked", timeout, TimeUnit.MILLISECONDS);
        return success != null && success;
    }

    @SuppressWarnings("unchecked")
    public void releaseLock(String lockKey) {
        Boolean delete = xddCloudCacheClient.delete(lockKey);
        log.info("待释放锁:{},释放锁:{}", lockKey, delete);
    }

    @SuppressWarnings("unchecked")
    public void releaseAllLock(List<String> lockKeys) {
        Long delete = xddCloudCacheClient.delete(lockKeys);
        log.info("持有锁:{},释放所有锁:{}", lockKeys.size(), delete);
    }
}
